<?php
/**
 * User: xialei
 * Date: 2016/7/2 0002
 * Time: 14:39
 */

namespace app\modules\api\controllers;


use app\models\Playlog;
use app\models\Prize;
use app\models\User;
use app\models\Win;
use yii\base\UserException;
use yii\db\ActiveQuery;
use yii\rest\Controller;
use yii\web\BadRequestHttpException;

class PrizeController extends Controller
{
    /**
     * 抽奖
     */
    public function actionAward()
    {
        //获取奖品列表
        $win = static::getWinByOpenid(\Yii::$app->user->id, true);
        if (!empty($win)) {
            return $win;
        }
        //检测是否摇过
        $play = Playlog::findOne(['openid' => \Yii::$app->user->id]);
        if (!empty($play)) {
            throw new UserException('您已经抽过奖啦!');
        }

        $prizeIDs = [];
        $prizeMap = Prize::find()->select(['prizeId', 'chance'])->asArray()->all();
        foreach ($prizeMap as $map) {
            for ($i = 0; $i < $map['chance']; $i++) {
                $prizeIDs[] = $map['prizeId'];
            }
        }
        $prizeId = $prizeIDs[array_rand($prizeIDs, 1)];

        /** @var Prize $prize */
        $prize = Prize::findOne($prizeId);

        $win = new Win();
        $win->prizeId = $prizeId;
        $log = new Playlog();
        if (!$win->save()) {
            $log->isAward = 0;
            $log->save();
            throw new UserException('很遗憾，没有中奖', 1);
        }
        $log->isAward = 1;
        $log->save();
        return array_merge($win->attributes, ['prize' => $prize->attributes]);
    }

    /**
     * 中奖列表
     * @param int $max
     * @param int $size
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionWins($max = 0, $size = 30)
    {
        $query = User::find()->limit($size)->orderBy(['{{%win}}.createdAt' => SORT_DESC]);
        if ($max > 0) {
            $query->andWhere(['<', '{{%win}}.createdAt', $max]);
        }
        $query->select(['{{%user}}.openid', 'nickname', 'phone', 'isExchange']);
        $query->innerJoinWith(['win.prize']);

        $data = $query->asArray()->all();
        foreach ($data as &$row) {
            $row['title'] = $row['win']['prize']['title'];
            if (!empty($row['phone'])) {
                $row['phone'] = substr_replace($row['phone'], '****', 3, 4);
            }
        }
        return $data;
    }

    /**
     * 领奖
     * @return array
     * @throws BadRequestHttpException
     * @throws UserException
     */
    public function actionExchange()
    {
        $data = \Yii::$app->request->getBodyParams();
        //检测是否中奖
        $win = static::getWinByOpenid(\Yii::$app->user->id);
        if (empty($win)) {
            throw new BadRequestHttpException('您没有中奖', 400);
        }

        /** @var User $user */
        $user = User::findOne(\Yii::$app->user->id);
        $user->setAttributes($data);
        if (!preg_match('/^1[3-9]\d{9}$/', $user->phone)) {
            throw new UserException('手机号码格式错误');
        }
        if ($user->code != $win->code) {
            throw new UserException('验证码错误!');
        }
        if (!$user->save()) {
            throw new UserException('领取失败');
        }
        return [
            'errcode' => 0,
            'errmsg' => '开户成功!'
        ];
    }

    /**
     * 查询用户是否中奖
     * @param $openid
     * @return Win
     */
    private function getWinByOpenid($openid, $asArray = false)
    {
        return Win::find()->joinWith(['prize'])->where(['openid' => $openid])->asArray($asArray)->one();
    }
}